from forest.server.api.basehandler import BaseHandler
from forest.server.models.node import Node
from forest.server.forms.node import NodeForm
import os

class NodeList(BaseHandler):
    def get(self):
        ''' listing all the nodes

        '''
        self.data['nodes'] = Node.query().all()
        return self.render_template('templates/nodelist.html')

    def post(self):
        ''' adding a new node
        '''
        return

class NodeGetTree(BaseHandler):
    def get(self):
        ''' listing all the nodes

        '''
        self.data['node'] = node = Node.query().filter(Node.uuid == self.request.get('uuid')).first()
        if node and hasattr(node, 'tree_file'):
            return os.path.join('http://%s/root/%s'% (self.app.config.get('server_name'), node.tree_file))
        return

    def post(self):
        ''' adding a new node
        '''
        return

class NodeView(BaseHandler):
    def get(self, id):
        ''' listing all the nodes

        '''
        self.data['node'] = node = Node.get(int(id))

        if self.request.get('alt') == 'tree':
            return os.path.join('http://%s/root/%s'% (self.app.config.get('server_name'), node.tree_file))

        return self.render_template('templates/nodeview.html')

    def post(self):
        ''' adding a new node
        '''
        return


class NodeNew(BaseHandler):
    def get(self):
        ''' listing all the nodes

        '''
        self.data['section_title'] = "New node"
        self.data['form'] = NodeForm()
        return self.render_template('templates/nodeedit.html')

    def post(self):
        ''' adding a new node
        '''
        self.data['section_title'] = "New node"
        self.data['form'] = form = NodeForm(self.request.POST)

        if form.validate():
            new_node = Node(**form.data)
            #form.populate_obj(new_node)
            new_node.put()

            self.redirect_to('node-node', id=new_node.id)

        return self.render_template('templates/nodeedit.html')


class NodeEdit(BaseHandler):
    def get(self, id):
        ''' listing all the nodes

        '''
        self.data['section_title'] = "Edit node"
        self.data['node'] = node = Node.get(int(id))
        self.data['form'] = NodeForm(None, node)
        return self.render_template('templates/nodeedit.html')

    def post(self, id):
        ''' adding a new node
        '''
        self.data['section_title'] = "Edit node"
        self.data['node'] = node = Node.get(int(id))
        self.data['form'] = form = NodeForm(self.request.POST, node)

        if form.validate():
            form.populate_obj(node)
            node.put()
            self.redirect_to('node-node', id=node.id)

        return self.render_template('templates/nodeedit.html')
